#include "widget.h"
#include "ui_widget.h"
#include <QTreeWidgetItem>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    ui->treeWidget->setHeaderLabel("动物");
    QTreeWidgetItem* cat = new QTreeWidgetItem();
    QTreeWidgetItem* dog = new QTreeWidgetItem();
    QTreeWidgetItem* bird = new QTreeWidgetItem();

    cat->setText(0, "猫");
    dog->setText(0, "狗");
    bird->setText(0, "鸟");
    ui->treeWidget->addTopLevelItem(cat);
    ui->treeWidget->addTopLevelItem(dog);
    ui->treeWidget->addTopLevelItem(bird);

    QTreeWidgetItem* cat1 = new QTreeWidgetItem();
    cat1->setText(0, "黑猫");
    cat->addChild(cat1);

    QTreeWidgetItem* cat2 = new QTreeWidgetItem();
    cat2->setText(0, "白猫");
    cat->addChild(cat2);

}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_pushButton_TopInsert_clicked()
{
    QString text = ui->lineEdit->text();
    QTreeWidgetItem* item = new QTreeWidgetItem();
    item->setText(0, text);
    ui->treeWidget->addTopLevelItem(item);
}

void Widget::on_pushButton_Insert_clicked()
{
    const QString& text = ui->lineEdit->text();
    QTreeWidgetItem* item = new QTreeWidgetItem();
    QTreeWidgetItem* curItem = ui->treeWidget->currentItem();
    item->setText(0, text);
    curItem->addChild(item);
}

void Widget::on_pushButton_remove_clicked()
{
    QTreeWidgetItem* curItem = ui->treeWidget->currentItem();
    if (curItem == nullptr)
        return;
    QTreeWidgetItem* parent = curItem->parent();

    if (parent) {
        parent->removeChild(curItem);
    } else {
        int index = ui->treeWidget->indexOfTopLevelItem(curItem);
        ui->treeWidget->takeTopLevelItem(index);
    }
}
